package gui;

import gui.peerObjects.peerObj;
import java.io.*;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import torrent.Torrent;

public class createTorrent extends javax.swing.JDialog {

  File inputFile;
  public static File outputFile = null;

  /**
   * Creates new form createTorrent
   */
  public createTorrent(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
  }

  /**
   * This method is called from within the constructor to initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is always
   * regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pieceLengthRadioButton = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        browseNotice = new javax.swing.JLabel();
        torrentFileName = new javax.swing.JTextField();
        browseButton = new javax.swing.JButton();
        pieceLengthNotice = new javax.swing.JLabel();
        autoPieceLength = new javax.swing.JRadioButton();
        manualPieceLength = new javax.swing.JRadioButton();
        sizeChooserComboBox = new javax.swing.JComboBox();
        chooseSizeNotice = new javax.swing.JLabel();
        createTorrentButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        trackerURLNotice = new javax.swing.JLabel();
        trackerURLName = new javax.swing.JTextField();

        jLabel1.setText("jLabel1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Customize your torrent file");

        browseNotice.setText("Browse for your file :");

        torrentFileName.setEditable(false);

        browseButton.setText("Browse...");
        browseButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                browseButtonMouseReleased(evt);
            }
        });

        pieceLengthNotice.setText("Piece Length :");

        pieceLengthRadioButton.add(autoPieceLength);
        autoPieceLength.setSelected(true);
        autoPieceLength.setText("Automatic");
        autoPieceLength.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        autoPieceLength.setOpaque(false);
        autoPieceLength.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                autoPieceLengthMouseReleased(evt);
            }
        });

        pieceLengthRadioButton.add(manualPieceLength);
        manualPieceLength.setText("Manual");
        manualPieceLength.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        manualPieceLength.setOpaque(false);
        manualPieceLength.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                manualPieceLengthMouseReleased(evt);
            }
        });

        sizeChooserComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "32     KB ", "64     KB ", "128   KB ", "256   KB ", "512   KB ", "1024 KB ", "2048 KB", "4096 KB" }));
        sizeChooserComboBox.setEnabled(false);

        chooseSizeNotice.setText("Choose custom size:");
        chooseSizeNotice.setEnabled(false);

        createTorrentButton.setText("Create Torrent");
        createTorrentButton.setEnabled(false);
        createTorrentButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                createTorrentButtonMouseReleased(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                cancelButtonMouseReleased(evt);
            }
        });

        trackerURLNotice.setText("Tracker URL:");

        trackerURLName.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                trackerURLNameKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(browseNotice)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(torrentFileName, javax.swing.GroupLayout.PREFERRED_SIZE, 301, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(browseButton))))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(pieceLengthNotice))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(trackerURLNotice))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(manualPieceLength)
                                .addGap(18, 18, 18)
                                .addComponent(chooseSizeNotice)
                                .addGap(18, 18, 18)
                                .addComponent(sizeChooserComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(autoPieceLength)
                            .addComponent(trackerURLName)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(94, 94, 94)
                        .addComponent(createTorrentButton)
                        .addGap(18, 18, 18)
                        .addComponent(cancelButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addComponent(browseNotice)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(torrentFileName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(browseButton))
                .addGap(7, 7, 7)
                .addComponent(pieceLengthNotice)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(autoPieceLength)
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(manualPieceLength)
                    .addComponent(chooseSizeNotice)
                    .addComponent(sizeChooserComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(trackerURLNotice)
                .addGap(3, 3, 3)
                .addComponent(trackerURLName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(createTorrentButton)
                    .addComponent(cancelButton))
                .addGap(19, 19, 19))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void browseButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_browseButtonMouseReleased
      JFileChooser fc = new JFileChooser("./");
      int buka = fc.showOpenDialog(fc);
      switch (buka) {
        case JFileChooser.APPROVE_OPTION:
          inputFile = fc.getSelectedFile();
          //buat file torrent
          peerObjects myPeer = new peerObjects();
          peerObj.myTorrent = new Torrent(inputFile);
          torrentFileName.setText(inputFile.getPath());
          enableCreateTorrent();
          break;
        case JFileChooser.CANCEL_OPTION:
          break;
        case JFileChooser.ERROR_OPTION:
          JOptionPane.showMessageDialog(null, "Error!  No file opened.", "Error", JOptionPane.ERROR_MESSAGE);
          break;
      }
    }//GEN-LAST:event_browseButtonMouseReleased

    private void manualPieceLengthMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_manualPieceLengthMouseReleased
      chooseSizeNotice.setEnabled(true);
      sizeChooserComboBox.setEnabled(true);
    }//GEN-LAST:event_manualPieceLengthMouseReleased

    private void autoPieceLengthMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_autoPieceLengthMouseReleased
      chooseSizeNotice.setEnabled(false);
      sizeChooserComboBox.setEnabled(false);
    }//GEN-LAST:event_autoPieceLengthMouseReleased

  public void enableCreateTorrent() {
    if (!torrentFileName.getText().isEmpty() && !trackerURLName.getText().isEmpty()) {
      createTorrentButton.setEnabled(true);
    } else {
      createTorrentButton.setEnabled(false);
    }
  }

  public void saveFile(File file, String text) throws IOException {
    try {
      try (FileWriter fis = new FileWriter(file)) {
        fis.write(text);
      }
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }
  }

  public int findAutoPieceSize(long fileLength) {
    int piecesize = 0;
    for (int i = 0; i <= 7; i++) {
      switch (i) {
        case 0:
          piecesize = 32768;
          break;
        case 1:
          piecesize = 65536;
          break;
        case 2:
          piecesize = 131072;
          break;
        case 3:
          piecesize = 262144;
          break;
        case 4:
          piecesize = 524288;
          break;
        case 5:
          piecesize = 1048576;
          break;
        case 6:
          piecesize = 2097512;
          break;
        case 7:
          piecesize = 4194304;
          break;
        default:
          break;
      }
      if (fileLength / piecesize <= 1000 || fileLength / piecesize <= 1500) {
        return piecesize;
      }
    }
    System.out.println("Auto piece size = " + piecesize);
    return piecesize;
  }

    private void createTorrentButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_createTorrentButtonMouseReleased
      JFileChooser fc = new JFileChooser("./");
      File sfile = new File(inputFile.getName().substring(0, inputFile.getName().indexOf('.')) + ".torrent");
      fc.setSelectedFile(sfile);
      int retVal = fc.showSaveDialog(createTorrent.this);
      if (retVal == JFileChooser.APPROVE_OPTION) {
        outputFile = fc.getSelectedFile();
        int piecesize = 0;
        if (autoPieceLength.isSelected()) {
          //mencari piecesize yang tepat
          piecesize = findAutoPieceSize(inputFile.length());
        } else {
          switch (sizeChooserComboBox.getSelectedIndex()) {
            case 0:
              piecesize = 32768;
              break;
            case 1:
              piecesize = 65536;
              break;
            case 2:
              piecesize = 131072;
              break;
            case 3:
              piecesize = 262144;
              break;
            case 4:
              piecesize = 524288;
              break;
            case 5:
              piecesize = 1048576;
              break;
            case 6:
              piecesize = 2097512;
              break;
            case 7:
              piecesize = 4194304;
              break;
            default:
              break;
          }
        }
        System.out.println("Size = " + piecesize);
        try {
          try {
            saveFile(outputFile, peerObjects.peerObj.myTorrent.writeFileTorrent(inputFile, trackerURLName.getText(), piecesize, (int) inputFile.length(), Torrent.SHA1b(Torrent.FileToByte(inputFile), piecesize)));
          } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
            Logger.getLogger(createTorrent.class.getName()).log(Level.SEVERE, null, ex);
          }
        } catch (IOException ex) {
          Logger.getLogger(createTorrent.class.getName()).log(Level.SEVERE, null, ex);
        }
        JOptionPane.showMessageDialog(rootPane, "Selesai membuat torrent!");
      }
      this.setEnabled(false);
      
      this.dispose();
    }//GEN-LAST:event_createTorrentButtonMouseReleased

    private void cancelButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseReleased
      this.dispose();
    }//GEN-LAST:event_cancelButtonMouseReleased

    private void trackerURLNameKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_trackerURLNameKeyReleased
      enableCreateTorrent();
    }//GEN-LAST:event_trackerURLNameKeyReleased

  public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {

      @Override
      public void run() {
        createTorrent dialog = new createTorrent(new javax.swing.JFrame(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {

          @Override
          public void windowClosing(java.awt.event.WindowEvent e) {
            System.exit(0);
          }
        });
        dialog.setVisible(true);
        
      }
    });
  }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JRadioButton autoPieceLength;
    private javax.swing.JButton browseButton;
    private javax.swing.JLabel browseNotice;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel chooseSizeNotice;
    private javax.swing.JButton createTorrentButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JRadioButton manualPieceLength;
    private javax.swing.JLabel pieceLengthNotice;
    private javax.swing.ButtonGroup pieceLengthRadioButton;
    private javax.swing.JComboBox sizeChooserComboBox;
    private javax.swing.JTextField torrentFileName;
    private javax.swing.JTextField trackerURLName;
    private javax.swing.JLabel trackerURLNotice;
    // End of variables declaration//GEN-END:variables
}
